﻿using RFID_EX_ETC_Client.Service;
using RFID_EX_ETC_Client.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RFID_EX_ETC_Client {
    public partial class LoginForm : Form {
        private MainService service;
        private bool loginSuccess = false;
        private static readonly string FORM_TITLE = GlobalVar.APP_NAME + "-->登录";

        internal MainService Service { get => service; set => service = value; }

        public LoginForm() {
            InitializeComponent();
        }

        private void LoginForm_Load(object sender, EventArgs e) {
            this.Text = FORM_TITLE;
        }

        private void btn_login_Click(object sender, EventArgs e) {
            string username = tb_UserName.Text.Trim();
            string passwd = tb_Password.Text.Trim();
            if ("".Equals(username) || "".Equals(passwd)) {
                MessageBox.Show("用户名或密码为空", "提示");
                return;
            }
            Service.Login(username, passwd, LoginCallBackDele);
        }

        private void LoginCallBackDele(bool isSuccess, string message, string result) {
            if (isSuccess) {
                //登录成功
                Console.WriteLine("登录成功");
                loginSuccess = true;
                CloseForm();
            } else {
                ShowMessageBox(message);
            }
        }

        private void btn_exit_Click(object sender, EventArgs e) {
            this.Close();
            System.Environment.Exit(0);
        }

        private delegate void ShowMessageBoxDelegate(string msg);
        private void ShowMessageBox(string msg) {
            if (this.InvokeRequired) {
                this.Invoke(new ShowMessageBoxDelegate(ShowMessageBox), msg);
            } else {
                MessageBox.Show(msg, "登录提示");
            }
        }

        private delegate void CloseFormDelegate();
        private void CloseForm() {
            if (this.InvokeRequired) {
                this.Invoke(new CloseFormDelegate(CloseForm));
            } else {
                Console.WriteLine("关闭窗口");
                this.Close();
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e) {
            if (!loginSuccess) {
                e.Cancel = true;
            }
            base.OnFormClosing(e);
        }

        public static bool HasLogin() {
            if ("".Equals(GlobalVar.Username)) {
                return false;
            }
            return true;
        }
    }
}
